import React, { useState, useRef, useEffect } from 'react';
import { connect } from 'dva';
import { QuillEditor } from 'components';
import { getFilePrefix } from '../../../utils/config';
import { Avatar, Row, Col, Card, Button, Form, Select, Modal, Tag, Divider, message } from 'antd';
import {
  StarOutlined, LikeFilled, MessageOutlined, FieldTimeOutlined, DislikeOutlined,
  StarFilled, LeftOutlined, LikeOutlined, DislikeFilled, EyeOutlined
} from '@ant-design/icons';
import Comment from './_comment';
import { history } from 'umi';
import { MdPreview, MdCatalog, } from 'md-editor-rt';
import 'md-editor-rt/lib/preview.css';
const { Meta } = Card;


const ArticleDetail = ({ dispatch, articleDetail, userInfo, collectionList }) => {
  const [isModal, setIsModal] = useState(false);
  const [form] = Form.useForm();
  const isLogin = userInfo && userInfo.userId > 0;
  const isAdmin = userInfo && userInfo.userType === 0;
  const editorRef = useRef(null);

  useEffect(() => {
    editorRef.current?.togglePreviewOnly(true);
    window.scrollTo(0, 0);
  }, [])

  const handleAction = (type, payload) => {
    if (!isLogin) {
      message.error('请先登录');
      return;
    }
    if (isAdmin) {
      message.error('管理员不能操作');
      return;
    }
    dispatch({ type, payload });
  };

  const likeArticle = () => {
    handleAction('articleDetail/likeArticle', {
      userId: userInfo.userId,
      articleId: articleDetail.articleId,
      isLike: !articleDetail.isLiked,
    });
  };

  const disLikeArticle = () => {
    handleAction('articleDetail/disLikeArticle', {
      userId: userInfo.userId,
      articleId: articleDetail.articleId,
      isDisLike: !articleDetail.isDisLiked,
    });
  };

  const addColl = (value) => {
    handleAction('articleDetail/collectArticle', {
      userId: userInfo.userId,
      articleId: articleDetail.articleId,
      isCollect: true,
      ...value,
    });
    setIsModal(false);
  };

  const cancelColl = (value) => {
    handleAction('articleDetail/collectArticle', {
      userId: userInfo.userId,
      articleId: articleDetail.articleId,
      isCollect: false,
    });
  };

  const followUser = (event) => {
    event.stopPropagation();
    handleAction('articleDetail/followUser', {
      userId: userInfo.userId,
      followerId: articleDetail.authorId,
      isFollow: !articleDetail.isFollowed,
    });
  };

  const renderContent = () => (
    articleDetail.markdownContent ?
      <MdPreview previewTheme={'cyanosis'} editorId={'preview-only'} modelValue={articleDetail.markdownContent} /> :
      <QuillEditor readOnly theme="bubble" value={articleDetail.content} />
  );

  return (
    <div style={{ marginTop: '1vh' }}>
      <Row>
        <Col span={4} >
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <LeftOutlined style={{ fontSize: '20px' }} onClick={() => window.history.back(-1)} />
          </div>
        </Col>
        <Col span={13} >
          <Card>
            <h1 style={{ textAlign: 'center', fontSize: 30, fontWeight: 700 }}>{articleDetail.title}</h1>
            {articleDetail.tags && articleDetail.tags.map((tag, index) => (
              <Tag color="blue" key={index}>{tag}</Tag>
            ))}
            <Divider />
            {renderContent()}
            <Row style={{ marginLeft: '1rem', }}>
              <Col span={2}>
                {articleDetail.isCollected ?
                  <StarFilled style={{ color: 'rgb(255,194,13)' }} onClick={cancelColl} /> :
                  <StarOutlined onClick={() => {
                    if (!isLogin) {
                      message.error('请先登录');
                      return;
                    }
                    if (isAdmin) {
                      message.error('管理员不能操作');
                      return;
                    }
                    setIsModal(true);
                  }} />
                }
                {" " + articleDetail.collectCount}
              </Col>
              <Col span={2} offset={1}>
                <EyeOutlined />{" " + articleDetail.view}
              </Col>
              <Col span={2} offset={1}>
                {articleDetail.isLiked ?
                  <LikeFilled style={{ color: 'red' }} onClick={likeArticle} /> :
                  <LikeOutlined onClick={likeArticle} />
                }
                {" " + articleDetail.like}
              </Col>
              <Col span={2} offset={1}>
                {articleDetail.isDisLiked ?
                  <DislikeFilled style={{ color: 'red' }} onClick={disLikeArticle} /> :
                  <DislikeOutlined onClick={disLikeArticle} />
                }
                {" " + articleDetail.disLike}
              </Col>
              <Col span={2} offset={1}>
                <MessageOutlined />{" " + articleDetail.commentCount}
              </Col>
              <Col offset={1}>
                <FieldTimeOutlined />{" " + articleDetail.updateTime}
              </Col>
            </Row>
            <Comment />
          </Card>
        </Col>
        <Col span={3} offset={2}>
          {/* todo: 增加按钮跳转
                    当前角色为自己的时候跳转到personalData中
                    当前角色非自己的时候跳转到attentionDetail中, 返回逻辑维持原样 */}
          <Card
            style={{ width: 210, cursor: articleDetail.authorId !== userInfo.userId && 'pointer', }}
            actions={[
              userInfo.userId === articleDetail.authorId || !isLogin ? null : (
                <Button
                  type={articleDetail.isFollowed ? 'danger' : 'primary'}
                  key="followButton"
                  onClick={followUser}
                >
                  {articleDetail.isFollowed ? '取消关注' : '关注'}
                </Button>
              )
            ]}
            // 修改这里的逻辑
            onClick={() => {
              articleDetail.authorId !== userInfo.userId &&
              history.push({ pathname: '/attentionList/attentionDetail', state: { targetUserId: articleDetail.authorId } })
            }}
          >
            <Meta
              avatar={<Avatar src={articleDetail.imgFilePath === "" ? "/image/login/defaultFilePath.png" : getFilePrefix() + articleDetail.imgFilePath} />}
              title={articleDetail.displayName}
              description={articleDetail.signature}
            />
          </Card>
        </Col>
      </Row>
      <Modal
        open={isModal}
        onCancel={() => setIsModal(false)}
        maskClosable={false}
        footer={[
          <Button key="back" onClick={() => setIsModal(false)}>取消</Button>,
          <Button key="submit" type="primary" onClick={() => form.submit()}>提交</Button>,
        ]}
      >
        <Form onFinish={addColl} form={form}>
          <Form.Item name="collectionId" label="收藏夹" rules={[{ required: true, message: '请选择收藏夹' }]}>
            <Select style={{ width: 350 }} placeholder="选择收藏夹(可搜索)"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={collectionList.map((item) => ({ label: item.collectionName, value: item.collectionId }))}
            >
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default connect(({ articleDetail, user, favorite }) => ({
  articleDetail: articleDetail.articleDetail,
  userInfo: user.userInfo,
  collectionList: favorite.collectionList,
}))(ArticleDetail);